<template>
  <div class="search">
    <form style="position: fixed; top: 0; width: 100%; z-index: 99" action="/">
      <van-search
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @input="onInput"
        @focus="onFocus"
      />
    </form>

    <div class="content">
      <!-- 进入网页就要显示搜索历史

     如果输入框有值就要显示搜索建议

     按下enter 键要显示搜索结果 -->

      <!-- 搜索结果 -->
      <search-result
        v-if="searchFlag"
        :value="value"
       
      ></search-result>

      <!-- 搜索建议 -->
      <search-suggest
        @search="onSearch"
        v-else-if="value"
        :value="value"
      ></search-suggest>

      <!-- 搜索历史 -->
      <search-history
        v-else
        :searchHistoryData="searchHistoryData"
        @cleanSingle="cleanSingle"
        @cleanAll="cleanAll"
      ></search-history>
    </div>
  </div>
</template>

<script>
import searchHistory from './components/searchHistory'
import searchSuggest from './components/searchSuggest'
import searchResult from './components/searchResult'

import { setItem, getItem, removeItem } from '@/utils/Storage'

export default {
  components: {
    searchHistory,
    searchSuggest,
    searchResult,
  },
  data() {
    return {
      value: '',
      searchFlag: false,
      searchHistoryData: getItem('searchHistoryData') || [],
      searchSuggestionData: [],
     
    }
  },
  methods: {
    //搜索历史展示
    onSearch(val) {
      this.searchFlag = true
      this.searchHistoryData.unshift(val)
      this.searchHistoryData = Array.from(new Set(this.searchHistoryData)) // 去重
      setItem('searchHistoryData', this.searchHistoryData)

      this.value = val
    },

    // 点击取消返回首页
    onCancel() {
      this.$router.push('/')
    },

    // 历史记录单个删除
    cleanSingle(index, item, clean) {
      if (clean) {
        this.searchHistoryData.splice(index, 1)
        setItem('searchHistoryData', this.searchHistoryData)
      } else {
       
        this.value = item
        console.log(this.historyItem, 9999)
        this.searchFlag = true
      }
    },

    // 历史记录全部删除
    cleanAll(clean) {
      if (clean) {
        this.searchHistoryData = []
        removeItem('searchHistoryData')
      }
    },

    onInput() {
      if (this.value == '') {
        this.searchFlag = false
      }
    },
    onFocus() {
       this.searchFlag = false
    },
  },
}
</script>

<style scoped lang='less'>
.content {
  padding-top: 120px;
}
</style>